<template>
  <el-select v-model="selectedUserId" filterable :placeholder="placeholder" @change="handleNodeChange" clearable>
    <el-option
      v-for="item in userList"
      :key="item.id"
      :label="item.nickname"
      :value="item.id" />
  </el-select>
</template>
<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import * as UserApi from '@/api/system/user'

defineOptions({ name: 'SystemUserSelect' })

const emits = defineEmits(['node-change'])

const props = defineProps({
  userId: {
    type: [Number, String],
    default: undefined,
  },
  placeholder: {
    type: String,
    default: '请选择'
  }
})

const selectedUserId = ref(props.userId ?? undefined)

const userList = ref<UserApi.UserVO[]>([])

const getList = async() => {
  const list = await UserApi.getSimpleUserList()
  userList.value = list

  // 如果有初始 userId，加载完成后立即 emit 对应用户信息
  if (props.userId !== undefined && props.userId !== null && props.userId !== '') {
    const info = userList.value.find(i => i.id == props.userId)
    if (info) {
      selectedUserId.value = info.id
      emits('node-change', info)
    } else {
      emits('node-change', null)
    }
  }

  return list
}

/** 处理员工选择 */
const handleNodeChange = async (item: number|any) => {
  if (!item || item === 0 || item === undefined) {
    emits('node-change', null)
    return
  }
  const info = userList.value.find(i=>i.id==item)
  emits('node-change', info || null)
}

/** 监听userId变化，变化时也 emit 对应用户信息 */
watch(() => props.userId, (newVal) => {
  selectedUserId.value = newVal ?? undefined

  if (newVal === undefined || newVal === null || newVal === '') {
    emits('node-change', null)
    return
  }

  const info = userList.value.find(i=>i.id==newVal)
  if (info) {
    emits('node-change', info)
  } else {
    // 如果列表还没加载或未找到，加载列表后再尝试 emit
    getList().then(() => {
      const info2 = userList.value.find(i=>i.id==newVal)
      emits('node-change', info2 || null)
    })
  }
})

/** 初始化 */
onMounted(async () => {
  await getList()
})
</script>